
package kaizone.haining.chaobohui.fragment;

import java.util.ArrayList;
import java.util.List;

import kaizone.haining.chaobohui.R;
import kaizone.haining.chaobohui.activity.CBHActivity;
import kaizone.haining.chaobohui.activity.DetailActivity;
import kaizone.haining.chaobohui.args.AppArgs;
import kaizone.haining.chaobohui.json.Banner;
import kaizone.haining.chaobohui.json.BannerDO;
import kaizone.haining.chaobohui.json.Data;
import kaizone.haining.chaobohui.json.NewListDO;
import kaizone.haining.chaobohui.json.NewsItem;
import kaizone.haining.chaobohui.json.Banner.PicModel;
import kaizone.haining.chaobohui.login.UserControl;
import kaizone.haining.chaobohui.net.DataControl;
import kaizone.haining.chaobohui.setup.APPAbout;
import kaizone.haining.chaobohui.util.ImageFetcher;
import kaizone.haining.chaobohui.util.Utils;
import kaizone.haining.chaobohui.widget.CBHItemView;
import kaizone.haining.chaobohui.widget.FlowPanelView;
import kaizone.haining.chaobohui.widget.SlideFrameLayout;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;

public class CBHHomeFragment extends Fragment implements DataControl.IDataUpdateListener,
        OnItemClickListener {

    public static final String DATA_SOURCE_URL = "http://api.dp-app.com/chao/remote/rest/query_news_list.htm";

    private FragmentManager mFragmentManager;

    private ArrayList<NewsItem> mData;

    private HomeAdapter mAdapter;

    private DataControl mDataControl;

    private ImageFetcher mImageFetcher;

    private FlowPanelView mTopView;

    // private AnimationImage animImage;
    private int mWidth;

    private int mHeight;

    public CBHHomeFragment(FragmentManager mgr) {
        mFragmentManager = mgr;
        mData = new ArrayList<NewsItem>();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Activity activity = getActivity();
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        final int dispalyWidth = dm.widthPixels;
        mWidth = dispalyWidth;
        float f = 34f / 67;
        mHeight = (int) (f * mWidth);
        initImageFecther();
    }

    public void initImageFecther() {
        if (getActivity() instanceof CBHActivity) {
            CBHActivity cbhActivity = (CBHActivity) getActivity();
            mImageFetcher = cbhActivity.getImageFetcher();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = (View) inflater.inflate(R.layout.cbh_fragment_list, null);
        ListView listview = (ListView) view.findViewById(R.id.listview);
        mAdapter = new HomeAdapter();
        // FrameLayout panel = SlideFrameLayout.newInstance(getActivity());
        // panel.setLayoutParams(new ListView.LayoutParams(mWidth, mHeight));
        // listview.addHeaderView(panel);
        mTopView = (FlowPanelView) inflater.inflate(R.layout.home_top, null);
        mTopView.setImageFetcher(mImageFetcher);
        mTopView.setViewFlowHeight(mHeight);
        listview.addHeaderView(mTopView);

        listview.setAdapter(mAdapter);

        listview.setOnItemClickListener(this);
        initControl();
        return view;
    }

    private void initControl() {
        mDataControl = new DataControl(getActivity());
        mDataControl.addChangeListener(this);
        mDataControl.exec(DATA_SOURCE_URL);

        if (AppArgs.sBannerDO == null) {
            mDataControl.exec(BannerDO.URL);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public Object backParse(String datastring, String requeststring) {
        if (TextUtils.isEmpty(datastring))
            return null;
        if (TextUtils.isEmpty(requeststring))
            return null;
        if (requeststring.equals(DATA_SOURCE_URL)) {
            NewListDO newsDO = NewListDO.parseJson(datastring);
            return newsDO;
        }//
        else if (requeststring.equals(BannerDO.URL)) {
            BannerDO bannerDO = BannerDO.parseJson(datastring);
            AppArgs.sBannerDO = bannerDO;
            return bannerDO;
        }//
        return null;
    }

    @Override
    public void foreUpdate(Object result, String requeststring) {
        if (result == null)
            return;
        if (result != null && result instanceof NewListDO) {
            NewListDO newListDO = (NewListDO) result;
            if (newListDO.success) {
                Data data = newListDO.getData();
                if (data != null) {
                    List<NewsItem> items = (List<NewsItem>) data.getItems();
                    mData.removeAll(mData);
                    for (int i = 0; i < 10; i++) {
                        mData.add(items.get(i));
                    }
                    mAdapter.notifyDataSetChanged();
                }

            }
        }//
        if (requeststring.equals(BannerDO.URL)) {
            BannerDO bannerDO = (BannerDO) result;
            Banner banner = bannerDO.getBanner(Banner.INDEX);
            if (banner == null)
                return;
            List<PicModel> items = banner.getPicModels();
            if (items == null || items.isEmpty())
                return;
            mTopView.update(items);
        }
    }

    @Override
    public void exception(Exception e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // if (position == 0) {
        // String urlString =
        // SlideFrameLayout.newInstance(getActivity()).getCurrentUrl();
        // Utils.openBrowser(getActivity(), urlString);
        // return;
        // }
        // int p = position - 1 < 0 ? 0 : position - 1;
        final int count = mData.size();
        if (position > count || position < 1)
            return;
        final int pos = position - 1;
        NewsItem news = mData.get(pos);
        int newsid = news.getId();
        DetailActivity.come(getActivity(), DetailActivity.FLAG_NEWS, newsid);
    }

    public void addIgnoredView(View v) {
        if (getActivity() instanceof CBHActivity) {
            ((CBHActivity) getActivity()).addIgnoredView(v);
        }
    }

    private class HomeAdapter extends BaseAdapter {

        private final int TYPE_IMG = 1;

        private final int TYPE_ITEM = 0;

        @Override
        public int getCount() {
            return mData != null ? mData.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return mData != null ? mData.get(position) : 0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemViewType(int position) {
            return position == -1 ? TYPE_IMG : TYPE_ITEM;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CBHItemView cbhItemView = null;

            int type = getItemViewType(position);
            if (convertView == null) {
                if (type == TYPE_IMG) {
                    FrameLayout panel = SlideFrameLayout.newInstance(getActivity());
                    panel.setLayoutParams(new ListView.LayoutParams(mWidth, mHeight));
                    // ViewPager image =
                    // (ViewPager)panel.findViewById(R.id.pager);
                    // image.setAdapter(new MyPagerAdapter());
                    convertView = panel;
                    addIgnoredView(panel);
                } else {
                    convertView = (CBHItemView) View.inflate(getActivity(), R.layout.item_home,
                            null);
                    if (getActivity() instanceof CBHActivity) {
                        CBHActivity cbhActivity = (CBHActivity) getActivity();
                        ((CBHItemView) convertView).setImageFetcher(cbhActivity.getImageFetcher());
                    }

                }
            }

            if (type == TYPE_IMG) {

            } else {
                // int p = position - 1 < 0 ? 0 : position - 1;
                cbhItemView = (CBHItemView) convertView;
                cbhItemView.setData(mData.get(position));
            }
            //
            return convertView;
        }
    }

    public static CBHHomeFragment newInstance(FragmentManager fm) {
        CBHHomeFragment f = new CBHHomeFragment(fm);
        return f;
    }
}
